import { Injectable, NotFoundException } from '@nestjs/common'
import { User } from '@boticord/users-client'
import { Repository } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm'
import { Resource, ResourceBoost } from '@boticord/resources-client'
import { ErrorCodes } from '@boticord/consts'

@Injectable()
export class BoostsService {
  constructor(
    @InjectRepository(User) private readonly users: Repository<User>,
    @InjectRepository(ResourceBoost) private readonly boosts: Repository<ResourceBoost>,
    @InjectRepository(Resource) private readonly resources: Repository<Resource>,
  ) {
  }

  async activateBoost(boostID: string, resourceID: string) {
    const boost = await this.boosts.findOne({ where: { id: boostID } })
    if (boost === null) {
      throw new NotFoundException({ code: ErrorCodes.UnknownBoost })
    }

    const resource = await this.resources.findOne({ where: { id: resourceID } })
    if (resource === null) {
      throw new NotFoundException({ code: ErrorCodes.UnknownResource })
    }

    boost.resource = resource
    resource.boosts = [ ...resource.boosts, boost ]

    await this.resources.save(resource)
    await this.boosts.save(boost)

    return [ resource, boost ] as const
  }

  async giveBoost(userID: string) {
    const user = await this.users.findOne({ where: { id: userID } })
    if (user === null) {
      throw new NotFoundException({ code: ErrorCodes.UnknownUser })
    }

    const boost = new ResourceBoost()
    boost.boughtAt = Date.now()
    boost.user = user
    boost.resource = undefined

    return this.boosts.save(boost)
  }
}